// 入库管理 API
import axios from 'axios'
import { getSalesOrderApiUrl } from '@/config/apiConfig'

export interface InboundListRow {
  id: number
  inboundOrderNumber: string
  inboundSubject: string
  inboundType: string
  inboundDate: string
  warehouseName: string
  inboundPersonnelName: string
  totalQuantity: number
  totalAmount: number
}

export interface InboundDetailItem {
  sequenceNumber: number
  itemNumber: string
  itemName: string
  specificationModel?: string
  unit: string
  brand?: string
  inboundQuantity: number
  mainUnitQuantity?: number
  batchNumber?: string
  productionDate?: string
  amount: number
}

export interface InboundDetailDto {
  id: number
  inboundOrderNumber: string
  inboundSubject: string
  inboundType: string
  inboundDate: string
  warehouseName: string
  inboundPersonnelName: string
  remarks?: string
  details: InboundDetailItem[]
}

export interface APIPageing<T> {
  code: number
  message: string
  pageIndex: number
  pageSize: number
  totalCount: number
  pageCount: number
  pageData: T[]
}

export interface APIResult<T> { code: number; message: string; data: T }

const client = axios.create({
  baseURL: 'http://localhost:5000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 添加请求拦截器，用于调试
client.interceptors.request.use(
  config => {
    console.log('发送请求:', config.method?.toUpperCase(), config.url, config.params)
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器，用于调试
client.interceptors.response.use(
  response => {
    console.log('收到响应:', response.status, response.data)
    return response
  },
  error => {
    console.error('响应错误:', error.response?.status, error.response?.data)
    return Promise.reject(error)
  }
)

export const inboundApi = {
  async list(pageIndex = 1, pageSize = 10) {
    try {
      console.log('调用入库API:', `/api/Inbound/list?pageIndex=${pageIndex}&pageSize=${pageSize}`)
      const res = await client.get('/api/Inbound/list', {
        params: { pageIndex, pageSize },
        timeout: 10000
      })
      console.log('API响应:', res.data)
      return res.data as APIResult<APIPageing<InboundListRow>>
    } catch (error) {
      console.error('API调用失败:', error)
      throw error
    }
  },
  async getById(id: number) {
    const res = await client.get(`/api/Inbound/${id}`)
    return res.data as APIResult<InboundDetailDto>
  },
  async create(payload: Partial<InboundDetailDto> & { warehouseId?: number }) {
    // map needed fields
    const body = {
      inboundSubject: payload.inboundSubject,
      inboundType: payload.inboundType,
      inboundDate: payload.inboundDate,
      warehouseId: payload.warehouseId ?? 1,
      remarks: payload.remarks,
      details: (payload.details || []).map(d => ({
        sequenceNumber: d.sequenceNumber,
        itemNumber: d.itemNumber,
        itemName: d.itemName,
        specificationModel: d.specificationModel,
        unit: d.unit,
        brand: d.brand,
        inboundQuantity: d.inboundQuantity,
        mainUnitQuantity: d.mainUnitQuantity,
        batchNumber: d.batchNumber,
        productionDate: d.productionDate,
        amount: d.amount
      }))
    }
    const res = await client.post('/api/Inbound', body)
    return res.data as APIResult<number>
  },
  async update(id: number, payload: Partial<InboundDetailDto> & { warehouseId?: number }) {
    const body = {
      inboundSubject: payload.inboundSubject,
      inboundType: payload.inboundType,
      inboundDate: payload.inboundDate,
      warehouseId: payload.warehouseId ?? 1,
      remarks: payload.remarks,
      details: (payload.details || []).map(d => ({
        sequenceNumber: d.sequenceNumber,
        itemNumber: d.itemNumber,
        itemName: d.itemName,
        specificationModel: d.specificationModel,
        unit: d.unit,
        brand: d.brand,
        inboundQuantity: d.inboundQuantity,
        mainUnitQuantity: d.mainUnitQuantity,
        batchNumber: d.batchNumber,
        productionDate: d.productionDate,
        amount: d.amount
      }))
    }
    const res = await client.put(`/api/Inbound/${id}`, body)
    return res.data as APIResult<boolean>
  },
  async delete(id: number) {
    const res = await client.delete(`/api/Inbound/${id}`)
    return res.data as APIResult<boolean>
  }
} 